#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>

int receive_message(int sock,char *buf,int len);
void handle_client(int sock);

#define MAX_BUFFER_SIZE 1024

int main()
{
	int fd = 0;
	int sockfd = 0;
	int ret = 0;
	struct sockaddr_in  addr;

	memset(&addr,0,sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = 6868;
	addr.sin_addr.s_addr = inet_addr("192.168.0.152");

	fd = socket(AF_INET,SOCK_STREAM,0);
	if(fd < 0)
	{
		perror("socket");
		exit(-1);
	}


	ret = bind(fd,(struct sockaddr *)&addr,sizeof(struct sockaddr));
	if(ret < 0)
	{
		perror("bind");
		exit(-1);
	}

	ret = listen(fd,5);
	if(ret < 0)
	{
		perror("listen");
		exit(-1);
	}


	sockfd = accept(fd,NULL,NULL);
	if(sockfd < 0)
	{
		perror("accept");
		exit(-1);
	}


	char buf[20] = {0};
	while(1)
	{
		handle_client(sockfd);
	}


	close(sockfd);
	close(fd);

	return 0;
}

void handle_client(int sock)
{
	char buffer[MAX_BUFFER_SIZE] = {0};
	int received = -1;

	while(1)
	{

		received = receive_message(sock,buffer,MAX_BUFFER_SIZE);
		if(received > 0)
		{
			buffer[received] = '\0';
			printf("buffer is %s\n",buffer);
		}
		sleep(1);

	}
}

int receive_message(int sock,char *buf,int len)
{
	int length = 0;
	int received = recv(sock,&length,4,0);
	/*
	 * if(length > len)
	 * {
	 * 需要处理，设置一个本消息剩余长度，待下次调用处理，本次不做处理
	 * }else
	 * {
	 * }*/

	received = recv(sock,buf,length,0);
	
	return received;

}














